package com.shiro.config;


import com.mysql.jdbc.log.Log;
import com.shiro.enity.User;
import com.shiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 进入被拦截的url，就会进这个info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 授权应该从数据库查出权限字段
        // info.addStringPermission("user:add");
        // 从 new SimpleAuthenticationInfo(queryUser, queryUser.getPwd(), "");传递过来第一个参数user最为subject
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        // 从数据库中获取验证权限
        String[] split = currentUser.getPerms().split(",");
        for (String s : split) {
            info.addStringPermission(s);
        }
        log.info("进入授权=》"+currentUser.getPerms());

        return info;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 模拟数据库中查出用户名、密码

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User currentUser = userService.queryUserByName((String)userToken.getUsername());
        // 验证用户名
        if (currentUser == null) {
            // 用户名不正确，就抛出UnknownAccountException
            return null;
        }
        log.info("password=>",currentUser.getPassword());
        // 密码验证,shiro完成，不需要用户判断.直接返回
        return new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(), "");

    }
}
